package cn.itsource.org.controller;

import cn.itsource.basic.annotation.PreAuthorize;
import cn.itsource.basic.page.PageList;
import cn.itsource.basic.page.Pageable;
import cn.itsource.org.domain.Department;
import cn.itsource.org.service.IDepartmentService;
import cn.itsource.basic.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/dept")
@Validated //开启单个参数的参数Springvalidation验证
public class DepartmentController {

    @Autowired
    private IDepartmentService departmentService;

    @GetMapping
    public AjaxResult findAll(){
        List<Department> all = departmentService.findAll();
        return AjaxResult.me().setResultObj(all);
    }

    @GetMapping("/{id}")
    public AjaxResult findOne(@PathVariable("id") Long id){
        Department dept = departmentService.findOne(id);
        return AjaxResult.me().setResultObj(dept);
    }

    @PutMapping
    public AjaxResult saveOrUpdate(@RequestBody @Valid Department department){
        departmentService.saveOrUpdate(department);
        return AjaxResult.me();
    }

    @DeleteMapping("/{id}")
    @PreAuthorize(name = "通过id删除部门",value = "dept:delete")
    public AjaxResult delete(@PathVariable Long id){
        departmentService.delete(id);
        return AjaxResult.me();
    }

    @PostMapping
    public AjaxResult pageQuery(@RequestBody Pageable pageable){
        PageList<Department> departmentPageList = departmentService.pageQuery(pageable);
        return AjaxResult.me().setResultObj(departmentPageList);
    }

    @PatchMapping
    public AjaxResult batchDelete(@RequestBody Map<String,String> map){
        departmentService.bachDelete(map);
        return AjaxResult.me();
    }

    @GetMapping("/tree")
    public AjaxResult tree(){
        return AjaxResult.me().setResultObj(departmentService.tree());
    }


    @GetMapping("/test")
    @Cacheable(cacheNames = "tree")
    public String test(){
       return "hello";
    }
}
